package com.bo;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ChristmasTree extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // 设置颜色
        g2d.setColor(Color.GREEN);

        // 绘制树的主干
        GeneralPath trunk = new GeneralPath();
        trunk.moveTo(150, 300);
        trunk.lineTo(160, 200);
        trunk.lineTo(140, 200);
        trunk.closePath();
        g2d.fill(trunk);

        // 绘制树的层次
        int levels = 10;
        int branch_length = 50;
        int angle = 30;

        for (int i = 0; i < levels; i++) {
            for (int j = 0; j < (int) Math.pow(2, i); j++) {
                GeneralPath branch = new GeneralPath();
                branch.moveTo(150, 300 - (i * 20));
                branch.lineTo(150 + (int) (branch_length * Math.sin(Math.toRadians(angle + (j * 2 * angle)))),
                        300 - (i * 20) - branch_length);
                branch.lineTo(150 + (int) (branch_length * Math.sin(Math.toRadians(-angle + (j * 2 * angle)))),
                        300 - (i * 20) - branch_length);
                branch.closePath();
                g2d.fill(branch);
            }
        }

        // 绘制树顶的星星
        g2d.setColor(Color.YELLOW);
        GeneralPath star = new GeneralPath();
        star.moveTo(150, 100);
        star.lineTo(140, 120);
        star.lineTo(160, 120);
        star.lineTo(150, 140);
        star.lineTo(140, 160);
        star.lineTo(150, 180);
        star.lineTo(160, 160);
        star.lineTo(150, 140);
        star.lineTo(140, 120);
        star.closePath();
        g2d.fill(star);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Christmas Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 400);
        frame.add(new ChristmasTree());
        frame.setVisible(true);
    }
}